#include "ThreatSpacePlayer.h"

ThreatSpacePlayer::ThreatSpacePlayer() : m_backupSearch(&ThreatHeuristic, 1, false)
{
	m_moveNumber = 0;
	m_playedFirst = true;
}

ThreatSpacePlayer::~ThreatSpacePlayer()
{
}

void ThreatSpacePlayer::Play(int player, Board board, Move &move)
{
	if(m_moveNumber == 0)
	{
		for(int a = 0; a < 19; a++)
		{
			for(int b = 0; b < 19; b++)
			{
				if(board[a][b] != 0) m_playedFirst = false;
			}
		}
	}

	if(m_playedFirst && m_moveNumber == 0)
	{
		// Play in center on first move
		move[0] = 9;
		move[1] = 9;
	}
	else
	{
		// Perform Threat Space Search Algorithm
		m_myThreats.clear();
		m_opponentThreats.clear();

		int t_opponent;
		if(player == 1) t_opponent = 2;
		else t_opponent = 1;

		FindAllThreats(player, board, m_myThreats);
		FindAllThreats(t_opponent, board, m_opponentThreats);

		m_myThreats.sort(ThreatCompare);
		m_opponentThreats.sort(ThreatCompare);
		
//		std::cout << "My Threats:\n";
//		for(std::list<Threat>::iterator it = m_myThreats.begin(); it != m_myThreats.end(); it++)
//		{
//			(*it).Print(std::cout);
//		}
//
//		std::cout << "\nOpponent Threats:\n";
//		for(std::list<Threat>::iterator it = m_opponentThreats.begin(); it != m_opponentThreats.end(); it++)
//		{
//			(*it).Print(std::cout);
//		}
//		std::cout << "\n";

		if(m_opponentThreats.empty()) // Opponent has no threats
		{
			// Look for winning threat sequence
			if(FindThreatSequence(player, board, m_myThreats, 0, move) > -1)
			{
				return;
			}

			// Perform traditional search
			m_backupSearch.Play(player, board, move);
		}
		else
		{
			// Look for winning move this turn
			int t_myDepth = FindThreatSequence(player, board, m_myThreats, 0, move);

			if(t_myDepth == 0)
			{
				return;
			}

			// Look for opponents winning move and block
			if(m_opponentThreats.front().m_type == THREAT_FIVE)
			{
				move[0] = m_opponentThreats.front().m_gainSquare[0];
				move[1] = m_opponentThreats.front().m_gainSquare[1];
				return;
			}

			if(t_myDepth == 2)
			{
				return;
			}

			if(CounterOpponentThreat(player, board, m_opponentThreats, move))
			{
				return;
			}

			if(t_myDepth > 0)
			{
				return;
			}

			m_backupSearch.Play(player, board, move);
		}
	}

	m_moveNumber++;
}

